package com.snail.app.config.service;

import com.snail.app.config.entity.DbDicDatabase;
import com.snail.app.config.rep.DbDicDatabaseRep;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @description
 * @date 2021/8/3
 * @autor houyanfeng
 */
@Service
@Transactional
public class DbDicDatabaseService {
    @Autowired
    private DbDicDatabaseRep dbDicDatabaseRep;

    public List<DbDicDatabase> list() {
        return dbDicDatabaseRep.findAll();
    }

    /**
     * 获取可连数据库信息的树结构字典
     */
    public Map<String, List<Object>> treeData() {
        Map<String, List<Object>> result = new LinkedHashMap<>();
        List<DbDicDatabase> dbDicDatabases = list();
        for (DbDicDatabase entity : dbDicDatabases) {
            if (!result.containsKey(entity.getName())) {
                result.put(entity.getName(), new ArrayList<Object>());
            }
            result.get(entity.getName()).add(entity);
        }
        result.put("dbType", new ArrayList<>(result.keySet()));
        return result;
    }

    /**
     * 获取数据库配置字典信息
     *
     * @param type    数据库类型关键字
     * @param version 版本
     * @return
     */
    public DbDicDatabase get(String type, String version) {
        List<DbDicDatabase> list = dbDicDatabaseRep.execHql("from DbDicDatabase where name='" + type + "' and version='" + version + "'");
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }
}
